<?php

namespace App\Services;

use App\Exceptions\BusinessException;
use App\Helpers\AiFileUploadHelper;
use App\Models\AiApp;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use Ninex\Lib\Http\Services\LibService;

class ApiService extends LibService
{
    public function info()
    {
        $app = auth()->guard('aiapp')->user();
        return [
            'expire_at' => Carbon::parse($app->expire_at)->format('Y-m-d H:i:s'),
            'tokens' => [
                ['type'=>'image','surplus'=>$app->image_token,'usage' => $app->used_image_token],
                ['type'=>'plus','surplus'=>$app->plus_token,'usage' => $app->used_plus_token],
                ['type'=>'max','surplus'=>$app->max_token,'usage' => $app->used_max_token],
            ]
        ];
    }
    public function token($params)
    {

        if($id = Arr::get($params,'debug'))
        {
            $app = AiApp::find($id);
        }else{
            if(!$appkey = Arr::get($params,'app_key')){
                throw new BusinessException('app_key不能为空');
            }

            if(!$timestamp = Arr::get($params,'timestamp')){
                throw new BusinessException('timestamp不能为空');
            }
            if(Carbon::now()->timestamp - $timestamp > 120){
                throw new BusinessException('timestamp已过期' );
            }
            if(!$signature = Arr::get($params,'signature')){
                throw new BusinessException('signature不能为空');
            }
            $app = AiApp::where('app_key',$appkey)->first();
            if(empty($app)){
                throw new BusinessException('APP不存在');
            }
            if($signature != strtolower(md5($appkey.$timestamp.$app->app_secret))){
                throw new BusinessException('signature错误');
            }
        }
        if (empty($app) || !$token = auth()->guard('aiapp')->login($app)) {
            throw new BusinessException('认证失败',401);
        }
        $appTokenKey = 'token:'.$app->id;
        if($lastUuid = Cache::get($appTokenKey)){
            Cache::forget($lastUuid);//作废原有的token
        }
        $expires_in = auth()->guard('aiapp')->factory()->getTTL() * 60;
        $uuid = Str::uuid()->toString();
        Cache::put($uuid,$token,$expires_in);
        Cache::put($appTokenKey,$uuid,$expires_in);
        \Log::info($app->name.'生成token:'.$uuid);
        return [
            'access_token' => $uuid,
            'token_type' => 'bearer',
            'expires_in' => $expires_in
        ];
    }

    public function upload(Request $request)
    {
        //获取上传的文件
        $file = $request->file('file');
        if(!$file->isValid()){
            throw new BusinessException('文件上传失败');
        }
        if (!in_array($file->getClientOriginalExtension(),['doc','docx','wps','ppt','pptx','xls','xlsx','md','txt','pdf'])) {
            throw new BusinessException('文件格式错误');
        }
        //获取文件路径
        $originalFilePath = $file->getRealPath();
        //按原后缀名存储到storage里为临时文件
        $fileName = Str::uuid().'.'.$file->getClientOriginalExtension();
        $filePath = storage_path('app/public/files/'.$fileName);
        move_uploaded_file($originalFilePath,$filePath);
        $res = AiFileUploadHelper::ApplyFileUploadLease($filePath);
        AiFileUploadHelper::UploadFile( $res->param->url,$filePath,$res->param->headers);
        $fileId = AiFileUploadHelper::AddFile($res->fileUploadLeaseId);
        //@unlink($filePath);
        return [
            'file_id' => $fileId
        ];
    }

    public function DescribeFile($file_id)
    {
        return AiFileUploadHelper::CheckFile($file_id);
    }
}
